package com.shushan.util;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseActivity;
import com.shushan.home.TabHomeActivity;
import com.shushan.lockscreen.bean.AppInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: SystemUtils
 * @Desciption: 工具类
 * @author: yichaohua
 * @date: 2018-05-25
 */
public class SystemUtils {

    private static final String TAG = "SystemUtils";

    private final static String [] allowSparePackName = {"com.huawei.android.internal.app","com.huawei.systemmanager"};

    /**
     * 判断本应用是否存活
     * 如果需要判断本应用是否在后台还是前台用getRunningTask
     * */
    public static boolean isAppALive(Context mContext, String packageName){
        boolean isAPPRunning = false;
        // 获取activity管理对象
        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        // 获取所有正在运行的app
        List<ActivityManager.RunningAppProcessInfo> appProcessInfoList = activityManager.getRunningAppProcesses();
        // 遍历，进程名即包名
        for(ActivityManager.RunningAppProcessInfo appInfo : appProcessInfoList){
            if(packageName.equals(appInfo.processName)){
                isAPPRunning = true;
                break;
            }
        }
        return isAPPRunning;
    }

    /**
     * 判断某个服务是否正在运行的方法
     *
     * @param mContext
     * @param serviceName
     *            是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    public static boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = activityManager.getRunningServices(10000);
        if (TextUtils.isEmpty(serviceName) || myList.size() <= 0) {
            return false;
        }

        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }

        return isWork;
    }

    public static String getProcessName(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo proInfo : runningApps) {
            if (proInfo.pid == android.os.Process.myPid()) {
                if (proInfo.processName != null) {
                    return proInfo.processName;
                }
            }
        }
        return null;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static boolean checkUsagePermission(Context context) {
        AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(),context.getPackageName());
        return mode == AppOpsManager.MODE_ALLOWED;
    }

    public static boolean isOpenPack(Context context,String packName){
        if(context == null || TextUtils.isEmpty(packName)){
            return false;
        }

        if(ControlUtil.isContactsPack(context,packName)
                || ControlUtil.isMMSPack(context,packName)){
            return true;
        }

        return false;
    }

    public static List<AppInfo> getUsePackages(Context context) {
        if(context == null){
            return null;
        }
        PackageManager packageManager = context.getPackageManager();
        if(packageManager == null){
            return null;
        }

        Log.d(TAG,"getUsePackages start " + DateUtils.getNowDate());
        List<AppInfo> AppInfoList = new ArrayList<AppInfo>();

        // 获取已经安装的所有应用, PackageInfo　系统类，包含应用信息
        List<PackageInfo> packages = packageManager.getInstalledPackages(0);
        for (int i = 0; i < packages.size(); i++) {
            PackageInfo packageInfo = packages.get(i);
            if(packageInfo.packageName.equals(context.getPackageName())){
                continue;
            }
            if (isOpenPack(context,packageInfo.packageName)
                    || ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)) { //非系统应用和联系人
                AppInfo appInfo = new AppInfo();
                appInfo.setLabel(packageInfo.applicationInfo.loadLabel(packageManager).toString());
                appInfo.setPackageName(packageInfo.packageName);
                appInfo.setVersionName(packageInfo.versionName);//获取应用版本名
                appInfo.setVersionCode(packageInfo.versionCode);//获取应用版本号
                appInfo.setIcon(packageInfo.applicationInfo.loadIcon(packageManager));

                AppInfoList.add(appInfo);
            }
        }
        Log.d(TAG,"getUsePackages end " + DateUtils.getNowDate());
        return AppInfoList;
    }

    public static List<AppInfo> getAllowUsePackages(Context context) {
        if(context == null){
            return null;
        }

        PackageManager packageManager = context.getPackageManager();
        if(packageManager == null){
            return null;
        }
        Log.d(TAG,"getUsePackages start " + DateUtils.getNowDate());
        List<AppInfo> AppInfoList = new ArrayList<AppInfo>();

        // 获取已经安装的所有应用, PackageInfo　系统类，包含应用信息
        List<PackageInfo> packages = packageManager.getInstalledPackages(0);
        for (int i = 0; i < packages.size(); i++) {
            PackageInfo packageInfo = packages.get(i);
            if(packageInfo.packageName.equals(context.getPackageName())){
                continue;
            }

            boolean isBlack = ControlUtil.containPackage(false,packageInfo.packageName);
            if (((isOpenPack(context,packageInfo.packageName)
                    || (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0))
                    && !isBlack) { //非系统应用
                AppInfo appInfo = new AppInfo();
                appInfo.setLabel(packageInfo.applicationInfo.loadLabel(packageManager).toString());
                appInfo.setPackageName(packageInfo.packageName);
                appInfo.setVersionName(packageInfo.versionName);//获取应用版本名
                appInfo.setVersionCode(packageInfo.versionCode);//获取应用版本号
                appInfo.setIcon(packageInfo.applicationInfo.loadIcon(packageManager));

                AppInfoList.add(appInfo);
            }
        }
        Log.d(TAG,"getUsePackages end " + DateUtils.getNowDate());
        return AppInfoList;
    }

    public static List<AppInfo> getUsePackages(boolean isWhite,Context context) {
        if(context == null){
            return null;
        }

        PackageManager packageManager = context.getPackageManager();
        if(packageManager == null){
            return null;
        }
        Log.d(TAG,"getUsePackages start " + DateUtils.getNowDate());
        List<AppInfo> AppInfoList = new ArrayList<AppInfo>();

        // 获取已经安装的所有应用, PackageInfo　系统类，包含应用信息
        List<PackageInfo> packages = packageManager.getInstalledPackages(0);
        for (int i = 0; i < packages.size(); i++) {
            PackageInfo packageInfo = packages.get(i);
            if(packageInfo.packageName.equals(context.getPackageName())){
                continue;
            }

            boolean isContain = ControlUtil.containPackage(isWhite,packageInfo.packageName);

            if (((isOpenPack(context,packageInfo.packageName) || (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0))
                    && isContain) {
                AppInfo appInfo = new AppInfo();
                appInfo.setLabel(packageInfo.applicationInfo.loadLabel(packageManager).toString());
                appInfo.setPackageName(packageInfo.packageName);
                appInfo.setVersionName(packageInfo.versionName);//获取应用版本名
                appInfo.setVersionCode(packageInfo.versionCode);//获取应用版本号
                appInfo.setIcon(packageInfo.applicationInfo.loadIcon(packageManager));

                AppInfoList.add(appInfo);
            }
        }
        Log.d(TAG,"getUsePackages end " + DateUtils.getNowDate());
        return AppInfoList;
    }

    public static void startApp(Context context,String appPackageName){
        Log.i(TAG,"appPackageName=" + appPackageName);
        if(TextUtils.isEmpty(appPackageName)){
            return;
        }

        BaseActivity baseActivity = (BaseActivity) ActivityStackManager.getActivityStackManager().currentActivity();
        if(baseActivity != null){
            baseActivity.setAllowBack(true);
        }

        try{
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(appPackageName);
            if(intent != null){
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }else {
                Log.e(TAG,"intent == null");

                SystemUtils.sendForegActivity(context,TabHomeActivity.class);
            }

        }catch(Exception e){
            e.printStackTrace();
            if(baseActivity != null){
                baseActivity.setAllowBack(false);
            }

            ToastUtils.showToast(context, "请开启该应用的关联启动后再尝试");
        }
    }

    public static void doStartApplicationWithPackageName(Context context,String packagename) {
        if(context == null){
            return;
        }

        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return;
        }

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);

        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = context.getPackageManager()
                .queryIntentActivities(resolveIntent, 0);

        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            // packagename = 参数packname
            String packageName = resolveinfo.activityInfo.packageName;
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
            String className = resolveinfo.activityInfo.name;
            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            // 设置ComponentName参数1:packagename参数2:MainActivity路径
            ComponentName cn = new ComponentName(packageName, className);

            BaseActivity baseActivity = (BaseActivity) ActivityStackManager.getActivityStackManager().currentActivity();
            if(baseActivity != null){
                baseActivity.setAllowBack(true);
            }

            intent.setComponent(cn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

    public static void sendForegActivity(Context context,Class<?> cls){
        Intent statIntent = new Intent(context,cls);
        statIntent.setAction("android.intent.action.MAIN");
        statIntent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, statIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        try {
            pendingIntent.send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    public static boolean isDarkNotificationBar(Context context){
        return !isColorSimilar(Color.BLACK,getNotificationColor(context));
    }

    private static final String DUMMY_TITLE = "DUMMY_TITLE";
    private static int titleColor;
    public static int getNotificationColorInternal(Context context){
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setContentTitle(DUMMY_TITLE);
        Notification notification = builder.build();

        ViewGroup notificationRoot = (ViewGroup) notification.contentView.apply(context,new FrameLayout(context));
        TextView title = notificationRoot.findViewById(android.R.id.title);
        if(title == null){//如果ROM厂商更改了默认的id
            //找到text为"DUMMY_TITLE"的TextView并获取其颜色
            iteratorView(notificationRoot,new Filter(){
                @Override
                public void filter(View view) {
                    TextView textView = (TextView) view;
                    if(view instanceof  TextView){
                        if(DUMMY_TITLE.equals(textView.getText().toString())){
                            titleColor = textView.getCurrentTextColor();
                        }
                    }
                }
            });

            return titleColor;
        }else {
            return title.getCurrentTextColor();
        }
    }

    public static int getNotificationColorCompat(Context context){
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        Notification notification = builder.build();

        int layoutId = notification.contentView.getLayoutId();
        ViewGroup notificationRoot = (ViewGroup) LayoutInflater.from(context).inflate(layoutId,null);
        TextView title = notificationRoot.findViewById(android.R.id.title);
        if(title == null){//如果ROM厂商更改了默认的id
            //先拿到所有的TextView
            final List<TextView> textViews = new ArrayList<TextView>();
            iteratorView(notificationRoot,new Filter(){
                @Override
                public void filter(View view) {
                    if(view instanceof  TextView){
                        textViews.add((TextView) view);
                    }
                }
            });

            //可以认为字号最大的TextView就是title
            float minTextSize = Integer.MIN_VALUE;
            int index = 0;
            for (int i = 0,j = textViews.size();i < j;i++){
                float currentSize = textViews.get(i).getTextSize();
                if(currentSize > minTextSize){
                    minTextSize = currentSize;
                    index = i;
                }
            }

            return textViews.get(index).getCurrentTextColor();
        }else {
            return title.getCurrentTextColor();
        }
    }

    private static void iteratorView(View view, Filter filter){
        if(view == null || filter == null){
            return;
        }

        filter.filter(view);
        if(view instanceof ViewGroup){
            ViewGroup containter = (ViewGroup) view;
            for (int i = 0,j = containter.getChildCount();i < j;i++){
                View child = containter.getChildAt(i);
                iteratorView(child,filter);
            }
        }
    }

    private interface  Filter{
        void filter(View view);
    }

    public static int getNotificationColor(Context context){
        if(context instanceof AppCompatActivity){
            return getNotificationColorCompat(context);
        }else {
            return getNotificationColorInternal(context);
        }
    }

    private static final double COLOR_THRESHOLD = 180.0;
    public static boolean isColorSimilar(int baseColor,int color){
        int simpleBaseColor = baseColor | 0xff000000;
        int simpleColor = color | 0xff000000;
        int baseRed = Color.red(simpleBaseColor) - Color.red(simpleColor);
        int baseGreen = Color.green(simpleBaseColor) - Color.green(simpleColor);
        int baseBlue = Color.blue(simpleBaseColor) - Color.blue(simpleColor);

        double value = Math.sqrt(baseRed*baseRed + baseGreen*baseGreen + baseBlue*baseBlue);
        if(value < COLOR_THRESHOLD){
            return true;
        }

        return false;
    }

    public static void openAppMarket(Context context,String packageName) {
        try {
            String str = "market://details?id=" + packageName;
            Intent localIntent = new Intent(Intent.ACTION_VIEW);
            localIntent.setData(Uri.parse(str));
            context.startActivity(localIntent);
        } catch (Exception e) {
            // 打开应用市场失败 可能是没有手机没有安装应用市场
            e.printStackTrace();
            ToastUtils.showToast(context,"您没有安装应用市场");
        }
    }

    public static boolean checkApkExist(Context context, String packageName){
        if(context == null){
            return false;
        }

        if (TextUtils.isEmpty(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                            PackageManager.GET_UNINSTALLED_PACKAGES);
            Log.d(TAG,info.toString());
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取渠道名
     * @param context
     * @return 如果没有获取成功，那么返回值为空
     */
    public static String getChannelName(Context context) {
        if (context == null) {
            return null;
        }

        String channelName = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                ApplicationInfo applicationInfo = packageManager.
                        getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        channelName = String.valueOf(applicationInfo.metaData.get("UMENG_CHANNEL"));
                    }
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return channelName;
    }

    public static boolean isSparePackName(String packageName){
        if(TextUtils.isEmpty(packageName)){
            return false;
        }

        for (String allowPackName : allowSparePackName){
            if(allowPackName.equals(packageName)){
                return true;
            }
        }

        return false;
    }
}
